package com.ecnu.system.service.impl;

import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.DateUtils;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.poi.ExcelUtil;
import com.ecnu.system.domain.Project;
import com.ecnu.system.domain.ProjectUser;
import com.ecnu.system.domain.dto.EvaluateListDTO;
import com.ecnu.system.domain.vo.EvaluateListInterVO;
import com.ecnu.system.domain.vo.EvaluateListVO;
import com.ecnu.system.domain.vo.ProjectUserVO;
import com.ecnu.system.domain.vo.ProjectViewVO;
import com.ecnu.system.mapper.ProjectUserMapper;
import com.ecnu.system.service.IProjectUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * ecnu_活动参与人表	 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-03-20
 */
@Service
public class ProjectUserServiceImpl extends ServiceImpl<ProjectUserMapper, ProjectUser> implements IProjectUserService {
    @Autowired
    private ProjectUserMapper projectUserMapper;

    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    @Override
    public TableDataInfo getProUser(String id, String nickName, PageDomain domain) {
        startPage(domain);
        List<ProjectUserVO> proUser = projectUserMapper.getProUser(id, nickName);
        return OtherUtil.tableSuccess(proUser);
    }

    @Override
    public void getProUserExcel(String id, HttpServletResponse response, Project project) {
        List<ProjectUserVO> proUser = projectUserMapper.getProUser(id, null);
        ExcelUtil<ProjectUserVO> util = new ExcelUtil<>(ProjectUserVO.class);
        util.exportExcel(response,proUser, project.getProName()+"活动用户数据");
    }

    @Override
    public List<ProjectViewVO> getReviewList(LoginUser loginUser, String name) {
        //添加一个权限控制--超管和系统管理能看到全部的 数据
        Long userId = loginUser.getUserId();
        boolean isUnauthorizedRole = loginUser.getUser().getRoles().stream()
                .noneMatch(role -> role.getRoleId() != 1L && role.getRoleId() != 2L);
        List<ProjectViewVO> projectViewVOS =new ArrayList<>();
        if (isUnauthorizedRole) {
            projectViewVOS = projectUserMapper.selectByReviewAdmin( name);

        }else {
            projectViewVOS = projectUserMapper.selectByReview(userId, name);

        }
        projectViewVOS.forEach(projectViewVO -> {
            if (projectViewVO.getStatus().equals("0")) {
                projectViewVO.setStatusName("通过");
                projectViewVO.setStatus("1");
            } else if (projectViewVO.getStatus().equals("1")) {
                projectViewVO.setStatusName("待审核");
                projectViewVO.setStatus("0");
            }

        });
        return projectViewVOS;
//        return null;
    }

    @Override
    public List<ProjectViewVO> mySubmissionList(LoginUser loginUser, String name) {

        List<ProjectViewVO> projectViewVOS = projectUserMapper.selectBySubmissionList(loginUser.getUserId(), name);
        projectViewVOS.forEach(projectViewVO -> {
            if (projectViewVO.getStatus().equals("0")) {
                projectViewVO.setStatusName("通过");
                projectViewVO.setStatus("1");
            } else if (projectViewVO.getStatus().equals("1")) {
                projectViewVO.setStatusName("待审核");
                projectViewVO.setStatus("0");
            }

        });
        return projectViewVOS;
    }


    /**
     * 评价模块接口
     *
     * @param dto
     * @param loginUser
     * @return
     */
    @Override
    public TableDataInfo selectEvaluateList(EvaluateListDTO dto, LoginUser loginUser) {
        Long roleId = loginUser.getUser().getRoles().get(0).getRoleId();
        Integer status = 1;
        if (roleId.equals(102L)) {
            status = 0;
        }

        startPage(dto.getPageDomain());
        List<EvaluateListInterVO> interVOS = projectUserMapper.selectEvaluateList(dto.getTitle(), loginUser.getUser().getUserId(), status);
        List<EvaluateListVO> copy = null;
        try {
//            //去重
//            interVOS= interVOS.stream()
//                    .collect(Collectors.collectingAndThen(
//                            Collectors.toMap(
//                                    item -> Arrays.asList(item.getProId(), item.getUserId()), // 根据 proId 和 userId 组合去重
//                                    item -> item,
//                                    (existing, replacement) -> existing // 如果遇到重复项，保留第一个出现的项
//                            ),
//                            map -> new ArrayList<>(map.values())
//                    ));
            interVOS.forEach(evaluateListInterVO  -> {
                String startTime = DateUtils.dateToString(evaluateListInterVO.getStartTime(), DateUtils.YYYY_MM_DD);
                String endTime = DateUtils.dateToString(evaluateListInterVO.getEndTime(), DateUtils.YYYY_MM_DD);
                evaluateListInterVO.setStartEndTime(startTime + "至" + endTime);
            });
            copy = OtherUtil.copy(interVOS, EvaluateListVO.class);

        } catch (InvocationTargetException | IllegalAccessException | InstantiationException |
                 NoSuchMethodException e) {
            log.error("评价  copy error:||" + e.getMessage());
        }

        return OtherUtil.tableSuccess2(copy, new PageInfo(interVOS).getTotal());
    }


}
